package com.zyc.app.woa.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.*;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.zyc.app.woa.*;
import com.zyc.app.woa.data.AccountInfo;
import com.zyc.app.woa.utils.Trace;
import com.zyc.app.woa.utils.WxUtils;

/**
 * Author: yingchang.zhang
 * Date  : 2014/11/26
 */
public class BrowserActivity extends FragmentActivity {
    private WebView mWebView;
    private ProgressBar mProgressBar;
    private ViewGroup mProgressContainer;
    private boolean mShowProgress = true;
    private String mCurrUrl;
    private String mOpenId;
    private int mTotalArticles;
    private int mDownloadArticlesNum = DOWNLOAD_NUM_LEVEL1;
    private Menu mActionMenu;
    private AccountInfo mAccountInfo;

    public static final int DOWNLOAD_NUM_LEVEL1 = 20;
    public static final int DOWNLOAD_NUM_LEVEL2 = 40;
    public static final int DOWNLOAD_NUM_LEVEL3 = 80;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browser);
        mWebView = (WebView) findViewById(R.id.web_content);
        mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
        mProgressContainer = (ViewGroup) findViewById(R.id.progress_bar_container);

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new WxJsBridge(), "WxJsBridge");
        mWebView.setWebViewClient(mWebViewClient);
        mWebView.loadUrl(WxUtils.buildSearchUrl("geek"));

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (mShowProgress) {
                    updateProgress(newProgress);
                } else {
                    if (100 == newProgress) {
                        mShowProgress = true;
                    }
                }

                super.onProgressChanged(view, newProgress);
            }
        });

        WxUtils.initWebCacheSettings(mWebView);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.add_offline_read).setTitle(getString(R.string.cache_recent_x_articles, mDownloadArticlesNum));
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.brower_action_bar, menu);
        mActionMenu = menu;
        menu.findItem(R.id.add_offline_read).setTitle(getString(R.string.cache_recent_x_articles, DOWNLOAD_NUM_LEVEL1));
        menu.findItem(R.id.recent_articles1).setTitle(getString(R.string.cache_recent_x_articles, DOWNLOAD_NUM_LEVEL1));
        menu.findItem(R.id.recent_articles2).setTitle(getString(R.string.cache_recent_x_articles, DOWNLOAD_NUM_LEVEL2));
        menu.findItem(R.id.recent_articles3).setTitle(getString(R.string.cache_recent_x_articles, DOWNLOAD_NUM_LEVEL3));
        menu.findItem(R.id.recent_articles_all).setTitle(getString(R.string.cache_all_x_articles, 0));

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            case R.id.add_offline_read:
                Trace.log("current url: " + mCurrUrl + " openId: " + mOpenId);
                mDownloadArticlesNum = WxConfig.DEFAULT_DOWNLOAD_SIZE;
                break;
            case R.id.recent_articles1:
                mDownloadArticlesNum = DOWNLOAD_NUM_LEVEL1;
                break;
            case R.id.recent_articles2:
                mDownloadArticlesNum = DOWNLOAD_NUM_LEVEL2;
                break;
            case R.id.recent_articles3:
                mDownloadArticlesNum = DOWNLOAD_NUM_LEVEL3;
                break;
            case R.id.recent_articles_all:
                mDownloadArticlesNum = mTotalArticles;
                break;
            default:
                break;
        }

        invalidateOptionsMenu();
        addAccountForReading();
        return true;
    }

    private void addAccountForReading() {
        if (null != mAccountInfo) {
            mAccountInfo.setSubscribeArticlesNum(mDownloadArticlesNum);
            SubscribeAccounts.addAccount(mAccountInfo);
            Intent intent = new Intent(this, DownloadService.class);
            intent.putExtra(WxConfig.ACCOUNT_INFO, mAccountInfo);
            startService(intent);
        }
    }

    private String getOpenId(String url) {
        final String tag = "openid=";
        int index = url.indexOf(tag);
        if (index > 0) {
            return url.substring(index + tag.length());
        }
        return null;
    }

    private void updateProgress(int newProgress) {
        if (100 == newProgress) {
            mProgressContainer.setVisibility(View.GONE);
        } else {
            if (View.GONE == mProgressContainer.getVisibility()) {
                mProgressContainer.setVisibility(View.VISIBLE);
            }
            mProgressBar.setProgress(newProgress);
        }
    }

    private void requestArticleNumbers() {
        new GetArticlesTotalNumberTask() {
            @Override
            protected void onPostExecute(Integer integer) {
                mTotalArticles = integer;
                MenuItem downloadAll = mActionMenu.findItem(R.id.recent_articles_all);
                downloadAll.setTitle(getString(R.string.cache_all_x_articles, integer));
                if (mTotalArticles <= DOWNLOAD_NUM_LEVEL1) {
                    mDownloadArticlesNum = mTotalArticles;
                    setActionMenuVisible(R.id.recent_articles1, false);
                    setActionMenuVisible(R.id.recent_articles2, false);
                    setActionMenuVisible(R.id.recent_articles3, false);
                } else if (mTotalArticles <= DOWNLOAD_NUM_LEVEL2) {
                    setActionMenuVisible(R.id.recent_articles1, true);
                    setActionMenuVisible(R.id.recent_articles2, false);
                    setActionMenuVisible(R.id.recent_articles3, false);
                } else if (mTotalArticles <= DOWNLOAD_NUM_LEVEL3) {
                    setActionMenuVisible(R.id.recent_articles1, true);
                    setActionMenuVisible(R.id.recent_articles2, true);
                    setActionMenuVisible(R.id.recent_articles3, false);
                } else {
                    setActionMenuVisible(R.id.recent_articles1, true);
                    setActionMenuVisible(R.id.recent_articles2, true);
                    setActionMenuVisible(R.id.recent_articles3, true);
                }
            }
        }.execute(mOpenId);
    }

    private void setActionMenuVisible(int id, boolean visible) {
        if (null != mActionMenu) {
            mActionMenu.findItem(id).setVisible(visible);
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mShowProgress = false;
            mWebView.goBack();
        } else {
            finish();
        }
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            mCurrUrl = url;
            Trace.log("shouldOverrideUrlLoading---url: " + url);
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            mCurrUrl = url;
            if (isAccountProfilePage(mCurrUrl)) {
                mOpenId = getOpenId(mCurrUrl);
                enableActionMenu(true);
            } else {
                enableActionMenu(false);
            }
            Trace.log("onPageStarted---url: " + url);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            Trace.log("onLoadResource---url: " + url);
            if (isSearchListPage(mCurrUrl)) {
                hideSearchHeader(view);
            } else if (isAccountProfilePage(mCurrUrl)) {
                hideAccountProfileHeader(view);
            }
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Trace.log("onPageFinished---url: " + url);
            if (isAccountProfilePage(mCurrUrl)) {
                collectAccountInfo(view);
                requestArticleNumbers();
            }
        }
    };

    private boolean isAccountProfilePage(String url) {
        return url.startsWith(WxUtils.PROFILE_BASE_URL);
    }

    private boolean isSearchListPage(String url) {
        return url.startsWith(WxUtils.SEARCH_BASE_URL);
    }

    private void enableActionMenu(boolean enable) {
        if (null != mActionMenu) {
            mActionMenu.findItem(R.id.add_offline_read).setVisible(enable);
        }
    }

    private void hideSearchHeader(WebView webView) {
        webView.loadUrl("javascript:" +
                "var sgNav=document.getElementsByClassName(\"mianNav\");" +
                " sgNav[0].style.display=\"none\";" +
                "var sgApp=document.getElementById(\"sogousearchappad\");" +
                " sgApp.style.display=\"none\";" +
                "var sgfooter=document.getElementById(\"footer\");" +
                " sgfooter.style.display=\"none\";");
    }

    private void hideAccountProfileHeader(WebView webView) {
        webView.loadUrl("javascript:" +
                "var pheader=document.getElementsByClassName(\"header\");" +
                "pheader[0].style.display=\"none\";");
    }

    private void collectAccountInfo(WebView webView) {
        webView.loadUrl("javascript:" +
                " var weixinId = weixinno.textContent;\n" +
                " var weixinDesc = info_box_txt1.textContent;" +
                " var weixinAvatar = $(\"img[src$=" + mOpenId + "]\").attr(\"src\");" +
                "window.WxJsBridge.onAccountInfoLoaded(weixinname, weixinId, weixinDesc, weixinAvatar)");
    }

    class WxJsBridge {
        public void onAccountInfoLoaded(String name, String id, String desc, String image) {
            mAccountInfo = new AccountInfo(name, mOpenId, id, desc, image, mCurrUrl);
            Trace.log("current accountInfo: " + mAccountInfo.toString());
        }
    }
}
